package com.qiyuesuo.oss.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.qiyuesuo.oss.entity.FileInfo;
import com.qiyuesuo.oss.service.FileService;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Arrays;


/**
 * @Author： xulinbo
 * @Description：
 * @Date： 18:16 2022/4/26
 **/
@RestController
@RequestMapping("/oss")
public class RestUploadController {

    @Autowired
    private FileService fileService;

    private final Logger logger = LoggerFactory.getLogger(RestUploadController.class);

    @PostMapping("/upload")

    public String uploadFile(
            @RequestParam("file") MultipartFile uploadfile) {
        logger.debug("Single file upload!");
        String message = "";
        if (uploadfile.isEmpty()) {
            return "文件上传有误";
        }
        try {
            message = fileService.saveUploadedFiles(uploadfile);
        } catch (IOException e) {
            return "文件上传有误";
        }
        return message;
    }

    @RequestMapping("/download")
    public void download(@Param("fileId") String fileId, HttpServletResponse response) throws IOException {
        FileInfo info = fileService.getFileInfo(fileId);
        FileReader reader = null;
        FileWriter writer = null;
        // 获取文件路径
        String filePath = info.getFilePath();
        // 文件名 + 后缀
        String fileName = info.getFileName();
        String[] split = fileName.split("\\.");
        String name = split[0];
        String fileExt = split[1];
        try {
            reader = new FileReader(filePath + fileName);
            writer = new FileWriter(filePath + name + "1"+fileExt);
            int i = 0;
            while ((i = reader.read()) != -1) {
                writer.write(i);
            }
            // 创建输出流对象
            ServletOutputStream outputStream = response.getOutputStream();
            //以字节数组的形式读取文件
            byte[] bytes = FileUtil.readBytes(filePath + fileName);
            // 设置返回内容格式
            response.setContentType("application/octet-stream");
            // 把文件名按UTF-8取出并按ISO8859-1编码，保证弹出窗口中的文件名中文不乱码
            // 中文不要太多，最多支持17个中文，因为header有150个字节限制。
            // 这一步一定要在读取文件之后进行，否则文件名会乱码，找不到文件
            fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
            // 设置下载弹窗的文件名和格式（文件名要包括名字和文件格式）
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            // 返回数据到输出流对象中
            outputStream.write(bytes);
            // 关闭流对象
            IoUtil.close(outputStream);
        } catch (Exception ignored) {

        }finally {
            if (reader != null){
                reader.close();
            }
            if (writer != null){
                writer.close();
            }
        }

    }

}
